package controllers;

import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.CategoryModel;
import models.LinkModel;

import systems.ConfigSystem;
import entities.Category;
import entities.Link;
import entities.SiteConfig;

public class SiteInfoServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		SiteConfig config = ConfigSystem.getConfigs();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		id = UrlHelper.getIdFromInfoUrl(id);
		
		LinkModel linkModel = LinkModel.getInstance();
		Link link = linkModel.get(id);
		
		if (link == null) {
			response.sendError(404);
			return;
		}
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> categories = categoryModel.listParents(link.getCategory());
		
		request.setAttribute("link", link);
		request.setAttribute("categories", categories);
		try {
			request.getRequestDispatcher("/templates/" + config.getTemplate() + "/pages/site-info.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
